<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自动记账 - 记账助手</title>
    <link rel="stylesheet" href="styles.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        /* 自动记账页面样式 */
        .auto-record-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }
        
        .back-btn {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .auto-record-title {
            font-size: 20px;
            font-weight: 600;
            margin: 0;
        }
        
        .auto-record-container {
            padding: 20px;
            max-width: 600px;
            margin: 0 auto;
        }
        
        .add-record-section {
            margin-bottom: 30px;
        }
        
        .add-record-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .add-record-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
        }
        
        .records-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .record-item {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            position: relative;
        }
        
        .record-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }
        
        .record-item.disabled {
            opacity: 0.6;
            background: #f8f9fa;
        }
        
        .record-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 12px;
        }
        
        .record-info {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;
        }
        
        .record-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: white;
        }
        
        .record-icon.expense {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
        }
        
        .record-icon.income {
            background: linear-gradient(135deg, #51cf66 0%, #40c057 100%);
        }
        
        .record-details {
            flex: 1;
        }
        
        .record-name {
            font-size: 16px;
            font-weight: 600;
            color: #2d3748;
            margin: 0 0 4px 0;
        }
        
        .record-amount {
            font-size: 18px;
            font-weight: 700;
            margin: 0 0 4px 0;
        }
        
        .record-amount.expense {
            color: #e53e3e;
        }
        
        .record-amount.income {
            color: #38a169;
        }
        
        .record-schedule {
            font-size: 12px;
            color: #718096;
        }
        
        .record-actions {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .toggle-switch {
            position: relative;
            width: 44px;
            height: 24px;
            background: #cbd5e0;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .toggle-switch.active {
            background: #667eea;
        }
        
        .toggle-switch::after {
            content: '';
            position: absolute;
            top: 2px;
            left: 2px;
            width: 20px;
            height: 20px;
            background: white;
            border-radius: 50%;
            transition: all 0.3s ease;
        }
        
        .toggle-switch.active::after {
            transform: translateX(20px);
        }
        
        .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            border: none;
            background: #f7fafc;
            color: #718096;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .action-btn:hover {
            background: #edf2f7;
            color: #4a5568;
        }
        
        .action-btn.danger:hover {
            background: #fed7d7;
            color: #e53e3e;
        }
        
        /* 弹窗样式 */
        .modal-content {
            border-radius: 12px;
            border: none;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
        }
        
        .modal-header {
            border-bottom: 1px solid #e2e8f0;
            padding: 20px 24px 16px;
        }
        
        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
        }
        
        .modal-body {
            padding: 20px 24px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #4a5568;
        }
        
        .form-input, .form-select {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        
        .form-input:focus, .form-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .form-row {
            display: flex;
            gap: 15px;
        }
        
        .form-row .form-group {
            flex: 1;
        }
        
        .type-selector {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .type-option {
            flex: 1;
            padding: 12px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
        }
        
        .type-option:hover {
            border-color: #667eea;
        }
        
        .type-option.selected {
            border-color: #667eea;
            background: #f0f4ff;
            color: #667eea;
        }
        
        .type-option.expense.selected {
            border-color: #e53e3e;
            background: #fed7d7;
            color: #e53e3e;
        }
        
        .type-option.income.selected {
            border-color: #38a169;
            background: #c6f6d5;
            color: #38a169;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .btn-outline {
            background: white;
            border: 1px solid #e2e8f0;
            color: #4a5568;
            padding: 12px 24px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-outline:hover {
            border-color: #667eea;
            color: #667eea;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #718096;
        }
        
        .empty-state-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }
        
        .empty-state-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #4a5568;
        }
        
        .empty-state-desc {
            font-size: 14px;
            line-height: 1.5;
        }
    </style>
</head>
<body>
    <div class="screen">
        <!-- 页面头部 -->
        <div class="auto-record-header">
            <button class="back-btn" onclick="history.back()">
                ‹
            </button>
            <h1 class="auto-record-title">自动记账</h1>
        </div>
        
        <!-- 主要内容 -->
        <div class="auto-record-container">
            <!-- 添加自动记账按钮 -->
            <div class="add-record-section">
                <button class="add-record-btn" id="add-record-btn">
                    <span style="font-size: 20px;">+</span>
                    添加自动记账
                </button>
            </div>
            
            <!-- 自动记账列表 -->
            <div class="records-list" id="records-list">
                <!-- 空状态 -->
                <div class="empty-state" id="empty-state">
                    <div class="empty-state-icon">⏰</div>
                    <div class="empty-state-title">暂无自动记账</div>
                    <div class="empty-state-desc">
                        设置自动记账后，系统会按照您的设定<br>
                        自动添加房贷、工资等固定收支记录
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 添加/编辑自动记账弹窗 -->
    <div class="modal fade" id="recordModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modal-title">添加自动记账</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="record-form">
                        <div class="form-group">
                            <label class="form-label">记账名称</label>
                            <input type="text" class="form-input" id="record-name" placeholder="如：房贷、工资等" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">收支类型</label>
                            <div class="type-selector">
                                <div class="type-option expense" data-type="expense">
                                    <div style="font-size: 20px; margin-bottom: 4px;">💸</div>
                                    <div>支出</div>
                                </div>
                                <div class="type-option income" data-type="income">
                                    <div style="font-size: 20px; margin-bottom: 4px;">💰</div>
                                    <div>收入</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">金额</label>
                            <input type="number" class="form-input" id="record-amount" placeholder="0.00" step="0.01" min="0" required>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">分类</label>
                            <select class="form-select" id="record-category" required>
                                <option value="">请选择分类</option>
                                <!-- 支出分类 -->
                                <optgroup label="支出分类" id="expense-categories">
                                    <option value="housing">住房</option>
                                    <option value="transport">交通</option>
                                    <option value="food">餐饮</option>
                                    <option value="shopping">购物</option>
                                    <option value="entertainment">娱乐</option>
                                    <option value="medical">医疗</option>
                                    <option value="education">教育</option>
                                    <option value="other-expense">其他支出</option>
                                </optgroup>
                                <!-- 收入分类 -->
                                <optgroup label="收入分类" id="income-categories">
                                    <option value="salary">工资</option>
                                    <option value="bonus">奖金</option>
                                    <option value="investment">投资收益</option>
                                    <option value="part-time">兼职</option>
                                    <option value="gift">礼金</option>
                                    <option value="other-income">其他收入</option>
                                </optgroup>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">执行频率</label>
                            <select class="form-select" id="record-frequency" required>
                                <option value="">请选择频率</option>
                                <option value="monthly">每月</option>
                                <option value="weekly">每周</option>
                            </select>
                        </div>
                        
                        <div class="form-row" id="schedule-options">
                            <!-- 每月选项 -->
                            <div class="form-group" id="monthly-option" style="display: none;">
                                <label class="form-label">每月第几天</label>
                                <select class="form-select" id="record-day">
                                    <option value="">请选择日期</option>
                                </select>
                            </div>
                            
                            <!-- 每周选项 -->
                            <div class="form-group" id="weekly-option" style="display: none;">
                                <label class="form-label">星期几</label>
                                <select class="form-select" id="record-weekday">
                                    <option value="">请选择星期</option>
                                    <option value="1">星期一</option>
                                    <option value="2">星期二</option>
                                    <option value="3">星期三</option>
                                    <option value="4">星期四</option>
                                    <option value="5">星期五</option>
                                    <option value="6">星期六</option>
                                    <option value="0">星期日</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">备注（可选）</label>
                            <input type="text" class="form-input" id="record-note" placeholder="添加备注信息">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirm-record">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 自动记账数据
        let autoRecords = JSON.parse(localStorage.getItem('autoRecords')) || [
            {
                id: 'demo1',
                name: '房贷还款',
                type: 'expense',
                amount: 8500.00,
                category: 'housing',
                frequency: 'monthly',
                day: 15,
                note: '每月15日银行自动扣款',
                enabled: true,
                createdAt: new Date().toISOString()
            },
            {
                id: 'demo2',
                name: '工资收入',
                type: 'income',
                amount: 12000.00,
                category: 'salary',
                frequency: 'monthly',
                day: 25,
                note: '每月25日发放工资',
                enabled: true,
                createdAt: new Date().toISOString()
            },
            {
                id: 'demo3',
                name: '生活费',
                type: 'expense',
                amount: 1500.00,
                category: 'food',
                frequency: 'weekly',
                weekday: 1,
                note: '每周一给生活费',
                enabled: true,
                createdAt: new Date().toISOString()
            },
            {
                id: 'demo4',
                name: '兼职收入',
                type: 'income',
                amount: 800.00,
                category: 'part-time',
                frequency: 'weekly',
                weekday: 5,
                note: '每周五兼职收入',
                enabled: false,
                createdAt: new Date().toISOString()
            }
        ];
        let editingRecordId = null;
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializePage();
            loadRecords();
        });
        
        // 初始化页面
        function initializePage() {
            // 生成日期选项（1-31日）
            const daySelect = document.getElementById('record-day');
            for (let i = 1; i <= 31; i++) {
                const option = document.createElement('option');
                option.value = i;
                option.textContent = `${i}日`;
                daySelect.appendChild(option);
            }
            
            // 绑定事件
            bindEvents();
        }
        
        // 绑定事件
        function bindEvents() {
            // 添加自动记账按钮
            document.getElementById('add-record-btn').addEventListener('click', function() {
                openRecordModal();
            });
            
            // 收支类型选择
            document.querySelectorAll('.type-option').forEach(option => {
                option.addEventListener('click', function() {
                    document.querySelectorAll('.type-option').forEach(opt => opt.classList.remove('selected'));
                    this.classList.add('selected');
                    updateCategoryOptions(this.dataset.type);
                });
            });
            
            // 频率选择
            document.getElementById('record-frequency').addEventListener('change', function() {
                updateScheduleOptions(this.value);
            });
            
            // 确认保存
            document.getElementById('confirm-record').addEventListener('click', function() {
                saveRecord();
            });
        }
        
        // 打开记账弹窗
        function openRecordModal(recordId = null) {
            editingRecordId = recordId;
            const modal = new bootstrap.Modal(document.getElementById('recordModal'));
            
            if (recordId) {
                // 编辑模式
                document.getElementById('modal-title').textContent = '编辑自动记账';
                const record = autoRecords.find(r => r.id === recordId);
                if (record) {
                    fillFormData(record);
                }
            } else {
                // 添加模式
                document.getElementById('modal-title').textContent = '添加自动记账';
                resetForm();
            }
            
            modal.show();
        }
        
        // 填充表单数据
        function fillFormData(record) {
            document.getElementById('record-name').value = record.name;
            document.getElementById('record-amount').value = record.amount;
            document.getElementById('record-category').value = record.category;
            document.getElementById('record-frequency').value = record.frequency;
            document.getElementById('record-note').value = record.note || '';
            
            // 设置收支类型
            document.querySelectorAll('.type-option').forEach(opt => opt.classList.remove('selected'));
            document.querySelector(`[data-type="${record.type}"]`).classList.add('selected');
            updateCategoryOptions(record.type);
            
            // 设置执行时间
            updateScheduleOptions(record.frequency);
            if (record.frequency === 'monthly') {
                document.getElementById('record-day').value = record.day;
            } else if (record.frequency === 'weekly') {
                document.getElementById('record-weekday').value = record.weekday;
            }
        }
        
        // 重置表单
        function resetForm() {
            document.getElementById('record-form').reset();
            document.querySelectorAll('.type-option').forEach(opt => opt.classList.remove('selected'));
            updateScheduleOptions('');
        }
        
        // 更新分类选项
        function updateCategoryOptions(type) {
            const expenseGroup = document.getElementById('expense-categories');
            const incomeGroup = document.getElementById('income-categories');
            
            if (type === 'expense') {
                expenseGroup.style.display = 'block';
                incomeGroup.style.display = 'none';
            } else if (type === 'income') {
                expenseGroup.style.display = 'none';
                incomeGroup.style.display = 'block';
            } else {
                expenseGroup.style.display = 'block';
                incomeGroup.style.display = 'block';
            }
            
            // 重置分类选择
            document.getElementById('record-category').value = '';
        }
        
        // 更新执行时间选项
        function updateScheduleOptions(frequency) {
            const monthlyOption = document.getElementById('monthly-option');
            const weeklyOption = document.getElementById('weekly-option');
            
            monthlyOption.style.display = frequency === 'monthly' ? 'block' : 'none';
            weeklyOption.style.display = frequency === 'weekly' ? 'block' : 'none';
            
            // 重置选择
            document.getElementById('record-day').value = '';
            document.getElementById('record-weekday').value = '';
        }
        
        // 保存记账配置
        function saveRecord() {
            const form = document.getElementById('record-form');
            const formData = new FormData(form);
            
            // 获取表单数据
            const name = document.getElementById('record-name').value.trim();
            const amount = parseFloat(document.getElementById('record-amount').value);
            const category = document.getElementById('record-category').value;
            const frequency = document.getElementById('record-frequency').value;
            const note = document.getElementById('record-note').value.trim();
            
            // 获取收支类型
            const selectedType = document.querySelector('.type-option.selected');
            if (!selectedType) {
                showAlert('请选择收支类型');
                return;
            }
            const type = selectedType.dataset.type;
            
            // 验证必填字段
            if (!name || !amount || !category || !frequency) {
                showAlert('请填写完整信息');
                return;
            }
            
            // 获取执行时间
            let day, weekday;
            if (frequency === 'monthly') {
                day = parseInt(document.getElementById('record-day').value);
                if (!day) {
                    showAlert('请选择执行日期');
                    return;
                }
            } else if (frequency === 'weekly') {
                weekday = parseInt(document.getElementById('record-weekday').value);
                if (weekday === undefined || weekday === null || weekday === '') {
                    showAlert('请选择执行星期');
                    return;
                }
            }
            
            // 创建记录对象
            const record = {
                id: editingRecordId || Date.now().toString(),
                name,
                type,
                amount,
                category,
                frequency,
                day: frequency === 'monthly' ? day : undefined,
                weekday: frequency === 'weekly' ? weekday : undefined,
                note,
                enabled: true,
                createdAt: editingRecordId ? autoRecords.find(r => r.id === editingRecordId).createdAt : new Date().toISOString()
            };
            
            // 保存记录
            if (editingRecordId) {
                // 更新现有记录
                const index = autoRecords.findIndex(r => r.id === editingRecordId);
                if (index !== -1) {
                    autoRecords[index] = record;
                }
            } else {
                // 添加新记录
                autoRecords.push(record);
            }
            
            // 保存到本地存储
            localStorage.setItem('autoRecords', JSON.stringify(autoRecords));
            
            // 刷新列表
            loadRecords();
            
            // 关闭弹窗
            const modal = bootstrap.Modal.getInstance(document.getElementById('recordModal'));
            modal.hide();
            
            showAlert(editingRecordId ? '自动记账更新成功' : '自动记账添加成功');
        }
        
        // 加载记录列表
        function loadRecords() {
            const recordsList = document.getElementById('records-list');
            const emptyState = document.getElementById('empty-state');
            
            if (autoRecords.length === 0) {
                emptyState.style.display = 'block';
                return;
            }
            
            emptyState.style.display = 'none';
            
            // 清空现有列表
            recordsList.innerHTML = '';
            
            // 渲染记录
            autoRecords.forEach(record => {
                const recordElement = createRecordElement(record);
                recordsList.appendChild(recordElement);
            });
        }
        
        // 创建记录元素
        function createRecordElement(record) {
            const div = document.createElement('div');
            div.className = `record-item ${record.enabled ? '' : 'disabled'}`;
            div.dataset.recordId = record.id;
            
            // 格式化执行时间
            let scheduleText = '';
            if (record.frequency === 'monthly') {
                scheduleText = `每月${record.day}日执行`;
            } else if (record.frequency === 'weekly') {
                const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
                scheduleText = `每周${weekdays[record.weekday]}执行`;
            }
            
            // 获取分类名称
            const categoryNames = {
                'housing': '住房',
                'transport': '交通',
                'food': '餐饮',
                'shopping': '购物',
                'entertainment': '娱乐',
                'medical': '医疗',
                'education': '教育',
                'other-expense': '其他支出',
                'salary': '工资',
                'bonus': '奖金',
                'investment': '投资收益',
                'part-time': '兼职',
                'gift': '礼金',
                'other-income': '其他收入'
            };
            
            div.innerHTML = `
                <div class="record-header">
                    <div class="record-info">
                        <div class="record-icon ${record.type}">
                            ${record.type === 'expense' ? '💸' : '💰'}
                        </div>
                        <div class="record-details">
                            <h3 class="record-name">${record.name}</h3>
                            <div class="record-amount ${record.type}">
                                ${record.type === 'expense' ? '-' : '+'}¥${record.amount.toFixed(2)}
                            </div>
                            <div class="record-schedule">
                                ${categoryNames[record.category] || record.category} · ${scheduleText}
                            </div>
                        </div>
                    </div>
                    <div class="record-actions">
                        <div class="toggle-switch ${record.enabled ? 'active' : ''}" onclick="toggleRecord('${record.id}')"></div>
                        <button class="action-btn" onclick="editRecord('${record.id}')">
                            ✏️
                        </button>
                        <button class="action-btn danger" onclick="deleteRecord('${record.id}')">
                            🗑️
                        </button>
                    </div>
                </div>
            `;
            
            return div;
        }
        
        // 切换记录启用状态
        function toggleRecord(recordId) {
            const record = autoRecords.find(r => r.id === recordId);
            if (record) {
                record.enabled = !record.enabled;
                localStorage.setItem('autoRecords', JSON.stringify(autoRecords));
                loadRecords();
                showAlert(record.enabled ? '自动记账已启用' : '自动记账已禁用');
            }
        }
        
        // 编辑记录
        function editRecord(recordId) {
            openRecordModal(recordId);
        }
        
        // 删除记录
        function deleteRecord(recordId) {
            const record = autoRecords.find(r => r.id === recordId);
            if (record && confirm(`确定要删除「${record.name}」的自动记账配置吗？`)) {
                autoRecords = autoRecords.filter(r => r.id !== recordId);
                localStorage.setItem('autoRecords', JSON.stringify(autoRecords));
                loadRecords();
                showAlert('自动记账删除成功');
            }
        }
        
        // 显示提示信息
        function showAlert(message) {
            const alertDiv = document.createElement('div');
            alertDiv.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                font-size: 14px;
                z-index: 9999;
                max-width: 300px;
                text-align: center;
            `;
            alertDiv.textContent = message;
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                document.body.removeChild(alertDiv);
            }, 2000);
        }
    </script>
</body>
</html>